<template>
    <div class="goods-evaluate-wrap">
      <div class="head">
        <div class="data">
          <p><span>100</span><span>人购买</span></p>
          <p><span>99.99%</span><span>好评率</span></p>
        </div>
        <div class="tags">
          <div class="dt">大家都在说：</div>
          <div class="dd">
            <a href="javascript:;" class="active">全部评价（{{total}}）</a>
            <a href="javascript:;">好吃（0）</a>
            <a href="javascript:;">便宜（0）</a>
            <a href="javascript:;">很好（0）</a>
            <a href="javascript:;">再来一次（0）</a>
            <a href="javascript:;">快递棒（0）</a>
          </div>
        </div>
      </div>
      <div class="filter-wrap">
        <!-- 过滤参数区域开始 -->
        <div class="filter-item">
          <span class="title">过滤选项：</span>
          <el-select
            v-model="filterValue"
            placeholder="全部"
            size="large"
            style="width: 260px"
            @change="handlerChangeFilter"
            @visible-change="handlerVisibleChange($event, 1)"
          >
            <el-option
              v-for="item in filterList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <!-- 过滤参数区域结束 -->

        <!-- 排序区域开始 -->
        <div class="filter-item">
          <span class="title">排序选择：</span>
          <el-select
            v-model="sortValue"
            placeholder="全部"
            size="large"
            style="width: 260px"
            @change="handlerChangeSort"
          >
            <el-option
              v-for="item in sortList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <!-- 排序区域结束 -->

        <!-- 综合筛选区域开始 -->
        <div class="filter-item">
          <el-button type="primary" size="large" @click="handlerShowCompositeFilter">综合筛选</el-button>
        </div>
        
        <!-- 综合筛选区域结束 -->
      </div>

      <!-- 骨架屏区域开始 -->
      <el-skeleton animated :loading="loading">
        <template #template>
          <div class="list-wrap">
            <div class="item-wrap" v-for="(item, index) in 3" :key="index">
              <!-- 顶部区域开始 -->
              <div class="top-wrap">
                <!-- 用户信息区域开始 -->
                <div class="user-wrap">
                  <el-skeleton-item variant="image" style="width: 43px; height: 43px;border-radius: 50%;margin-left: -3px;" />
                  <el-skeleton-item variant="p" style="width: 60px;margin-left: 10px;" />
                </div>
                <!-- 用户信息区域结束 -->

                <!-- 评分区域开始 -->
                <div class="score-wrap">
                  <el-skeleton-item variant="text" style="width: 100px;" />
                </div>
                <!-- 评分区域结束 -->
              </div>
              <!-- 顶部区域结束 -->

              <!-- 商品SKU区域 -->
              <el-skeleton-item class="goods-sku-wrap" style="width: 400px;margin: 10px 0;" />

              <div class="content-wrap">
                <div class="content">
                  <el-skeleton-item v-for="(item, index) in 3" :key="index"/>
                </div>
                <div class="time">
                  <el-skeleton-item style="width: 200px;"/>
                  <div>
                    <el-skeleton-item style="width: 30px;height: 20px;"/>
                    <el-skeleton-item style="width: 30px;height: 20px;margin-left: 6px;"/>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-skeleton>
      <!-- 骨架屏区域结束 -->
      
      <!-- 评价列表区域开始 -->
      <div class="list-wrap" v-if="goodsEvaluateList.length > 0">
        <div class="item-wrap" v-for="item in goodsEvaluateList" :key="item.id">
          <!-- 顶部区域开始 -->
          <div class="top-wrap">
            <!-- 用户信息区域开始 -->
            <div class="user-wrap">
              <img :src="global.FILE_DOMAIN + item.avatar_url" alt="">
              <span>{{formatUsername(item.username)}}</span>
            </div>
            <!-- 用户信息区域结束 -->

            <!-- 评分区域开始 -->
            <div class="score-wrap">
              <i class="iconfont icon-xingxing1" v-for="i in item.composite_score" :key="i"></i>
              <i class="iconfont icon-xingxing" v-for="i in (5-item.composite_score)" :key="i"></i>
            </div>
            <!-- 评分区域结束 -->
          </div>
          <!-- 顶部区域结束 -->

          <!-- 商品SKU区域 -->
          <div class="goods-sku-wrap">{{ item.goods_sku_text }}</div>

          <!-- 评价内容区域开始 -->
          <div class="content-wrap">
            <div class="content">{{ item.contents }}</div>

            <!-- 使用图片预览组件 -->
            <GoodsEvaluateImage v-if="item.image_url_items" :pictures="item.image_url_items" />

            <div class="time-wrap">
              <div>{{ item.create_time }}</div>
              <div class="action-wrap">
                <!-- 点赞区域 -->
                <div class="like-wrap">
                  <i class="iconfont icon-dianzan" @click="handlerLike(item)" ></i>
                  <span>{{ item.like_num }}</span>
                  <i class="like-tip" :class="{active: item.giveLike}">+1</i>
                  <!-- 应用动画 -->
                  <!-- animation-name: give-like; -->
                </div>

                <!-- 评论区域 -->
                <div class="item-wrap">
                  <i class="iconfont icon-pinglun"></i>
                  <span>评论</span>
                </div>

                <!-- 有用区域 -->
                <div class="useful-wrap" :class="{active: item.useful == 1}" @click="handlerUseful(item)">
                  <i class="iconfont icon-gou"></i>
                  <span>有用</span>
                </div>
              </div>
            </div>
          </div>
          <!-- 评价内容区域结束 -->
        </div>
      </div>
      <Empty v-if="!loading && goodsEvaluateList.length == 0" />
      <!-- 评价列表区域结束 -->

      <!-- 分页区域开始 -->
      <div class="page-wrap" v-if="total > 0">
        <el-pagination 
            background 
            layout="prev, pager, next" 
            :total="total"
            :page-size="params.page_size"
            :current-page="params.page"
            @current-change="handlerCurrentChange"
            />
      </div>
      <!-- 分页区域结束 -->

      <!-- 综合筛选弹层开始 -->
      <el-dialog
        title="综合筛选"
        :close-on-click-modal="false"
        :show-close="false"
        v-model="compositeFilterDialogVisible"
        width="80%"
        center
      >
        <div class="composite-filter-wrap">
          <div class="composite-filter-item" v-for="(item, index) in goodsOptionList" :key="index">
            <div class="title">{{item.name}}</div>
            <div class="content">
              <div 
                class="sku-item ellipsis-1"
                v-for="(value, index) in item.values" :key="index"
                :class="selectSkuTexts.includes(item.name+'：'+value) ? 'active' : ''"
                @click="handlerChangeCompositeFilter(item.name, value)"
              >
                {{ value }}
              </div>
            </div>
          </div>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handlerReset">重置</el-button>
            <el-button type="primary" @click="handlerConfirm">确定</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 综合筛选弹层结束 -->
    </div>
</template>
  
<script setup>
import { reqGoodsCommentListAPI, reqGoodsCommentTotalAPI, reqEditGoodsCommentAPI } from '@/apis/goodsEvaluate'
import { reqGetGoodsOptionListAPI } from '@/apis/goods'

import { ref, onMounted, reactive, inject } from 'vue'

import GoodsEvaluateImage from './GoodsEvaluateImage.vue'

import useScroll from '@/utils/useScroll'

import { ElNotification } from 'element-plus'


// --------------------- 综合过滤功能开始 ---------------------
const compositeFilterDialogVisible = ref(false)

// 定义选中的sku
const selectSkuTexts = ref([])

// 定义选中的sku
const selectSkuList = ref([])

// 处理显示综合筛选弹层
const handlerShowCompositeFilter = async () => {
  goodsOptionList.value = []
  const result = await reqGetGoodsOptionListAPI({goods_id: props.goods_id})
  const goodsOptionItems = result.data.goods_option_items != null ? result.data.goods_option_items : []
  goodsOptionItems.forEach(item => {
    item.values = item.value.split(',')
    goodsOptionList.value.push(item)
  });

  goodsOptionList.value = goodsOptionList.value.reverse()
  compositeFilterDialogVisible.value = true
}

// 处理选择综合筛选
const handlerChangeCompositeFilter = (name, value) => {
  // 过滤相同的数据
  selectSkuList.value = selectSkuList.value.filter(item => item.name != name)

  selectSkuList.value.push({name, value})
  selectSkuTexts.value = []
  selectSkuList.value.forEach((item) => {
    selectSkuTexts.value.push(item.name + '：' + item.value)
  })
}

// 重置数据
const handlerReset = () => {
    selectSkuTexts.value = []
    selectSkuList.value = []
}

// 确定综合筛选
const handlerConfirm = () => {
  if (selectSkuList.value.length > 0) {
    let goodsSkuText = selectSkuTexts.value
    if (selectSkuList.value[0].name != goodsOptionList.value[0].name) {
      params.goods_sku_text = goodsSkuText.reverse().join(' ')
    } else {
      params.goods_sku_text = goodsSkuText.join(' ')
    }
  }

  params.page = 1
	goodsEvaluateList.value = []
  goodsOptionList.value = []
  compositeFilterDialogVisible.value = false
  getGoodsEvaluateList()
}
// --------------------- 综合过滤功能结束 ---------------------



// --------------------- 定义全局变量开始 ---------------------
const {scrollToPosition} = useScroll()

// 获取全局对象
const global = inject('global')

// 接收商品ID
const props = defineProps({
  goods_id: {
    type: Number,
    default: () => 0
  }
})

// 请求参数
const params = reactive({
  goods_id: props.goods_id,
  goods_sku_id: 0,
  goods_sku_text: '',
  is_append: 'all',
  label_id: 0,
  is_image: 'all',
  composite_score: 0,
  sort_field: 'id',
  sort_type: 'desc',
  page: 1,
  page_size: 10
})

// 定义延时器
const timer = ref(null)

// 定义加载中变量
const loading = ref(false)
// --------------------- 定义全局变量结束 ---------------------



// 挂载页面完成
onMounted(() => {
  getGoodsEvaluateList()
})



// ------------------------ 商品评价点赞功能开始 -------------------------
// 处理点赞功能
const handlerLike = (item) => {
  // ------------------ 防抖处理 ------------------
	// 清除延时器
	clearTimeout(timer.value)
  // 重新启动延时器
	timer.value = setTimeout(async () => {
		item.giveLike = true
    item.like_num += 1
    const result = await reqEditGoodsCommentAPI({id: item.id, like_num: item.like_num})
    if (result.code == 200) {
      ElNotification({type: 'success', message: '点赞成功'})
    }

    setTimeout(() => {
      item.giveLike = false
    }, 300)

	}, 300)
}
// ------------------------ 商品评价点赞功能结束 -------------------------



// ------------------------ 商品评价有用功能结束 -------------------------
const handlerUseful = (item) => {
  item.useful = item.useful == 1 ? 0 : 1
  // ------------------ 防抖处理 ------------------
	// 清除延时器
	clearTimeout(timer.value)
  // 重新启动延时器
	timer.value = setTimeout(async () => {
    const result = await reqEditGoodsCommentAPI({id: item.id, useful: item.useful})
    if (result.code == 200) {
      ElNotification({type: 'success', message: '编辑成功'})
    }
  })
}
// ------------------------ 商品评价有用功能结束 -------------------------



// ------------------------ 商品评价选项功能开始 -------------------------
// 定义商品选项
const goodsOptionList = ref([])

// 选择 tab
const handlerVisibleChange = async (e, index) => {
  // 当 e 等于true的时候表示显示下拉框
  if (e) {
    // 选中全部
    if (index == 1) {
      await Promise.all([
        // 获取有图片的评价数量
        getGoodsEvaluateTotal({goods_id: props.goods_id, is_image: '1', mode: 'image'}),
        // 获取有追加的评价数量
        getGoodsEvaluateTotal({goods_id: props.goods_id, is_append: '1', mode: 'append'}),
        // 获取好评数量
        getGoodsEvaluateTotal({goods_id: props.goods_id, composite_score: 5, mode: 'praise'})
      ])
    }
  }
}

// 获取评价数量
const getGoodsEvaluateTotal = async (queryParam) => {
    // 请求数据
	const result = await reqGoodsCommentTotalAPI(queryParam)
    if (queryParam.mode == 'image') {
        filterList.value[1].label = '视频/图片('+ result.data.total +')'
    } else if (queryParam.mode == 'append') {
        filterList.value[2].label = '追评('+ result.data.total +')'
    } else if (queryParam.mode == 'praise') {
        filterList.value[3].label = '好评('+ result.data.total +')'
    }
}
// ------------------------ 商品评价选项功能结束 -------------------------



// ------------------------ 商品评价过滤功能开始 -------------------------
// 筛选值
const filterValue = ref(0)

// 过滤条件
const filterList = ref([
  { label: '全部', value: 0 },
  { label: '视频/图片(0)', value: 1 },
  { label: '追评(0)', value: 2 },
  { label: '好评(0)', value: 3 },
])

// 处理过滤
const handlerChangeFilter = (value) => {

  clearQueryParams()
  
  filterValue.value = value

  if (value == 1) { // 视频/图片
      params.is_image = '1'
  } else if (value == 2) { // 追评
      params.is_append = '1'
  } else if (value == 3) { // 好评
      params.composite_score = 5
  }

  params.page = 1
  getGoodsEvaluateList()
}

// 清除商品列表参数
const clearQueryParams = () => {
  params.goods_sku_id = 0
  params.is_append = 'all'
  params.label_id = 0
  params.is_image = 'all'
  params.composite_score = 0

	// params.sort_field = 'id'
	// params.sort_mode = 'desc'
	params.page = 1
	goodsEvaluateList.value = []
}
// ------------------------ 商品评价过滤功能结束 -------------------------


// ------------------------ 商品评价排序功能开始 -------------------------
// 排序值
const sortValue = ref(0)

// 排序条件
const sortList = ref([
    { label: '默认排序', value: 0 },
    { label: '评分高到低', value: 1 },
    { label: '评分低到高', value: 2 },
])

// 处理排序
const handlerChangeSort = (value) => {
  sortValue.value = value

  if (value == 1) { // 评分高到低
    params.sort_field = 'composite_score'
    params.sort_type = 'desc'
  } else if (value == 2) { // 评分低到高
    params.sort_field = 'composite_score'
    params.sort_type = 'asc'
  } else {
    params.sort_field = 'id'
    params.sort_type = 'desc'
  }

  params.page = 1
	goodsEvaluateList.value = []
  getGoodsEvaluateList()
}
// ------------------------ 商品评价排序功能结束 -------------------------


const formatUsername = (username) => {
  return username.substr(0, 1) + '****' + username.substr(-1)
}

// 记录
const goodsEvaluateList = ref([])
// 记录总条数
const total = ref(0)

// 请求商品评价数据
const getGoodsEvaluateList = async () => {
  loading.value = true
  const result = await reqGoodsCommentListAPI(params)
  if (result.code == 200) {
    goodsEvaluateList.value = result.data.goods_comments != null ? result.data.goods_comments : []
    total.value = result.data.total
    goodsEvaluateList.value.forEach((item) => {
      item.giveLike = false
    })
  }

  loading.value = false
}

// 翻页功能开始
const handlerCurrentChange = async (page) => {
  params.page = page
  scrollToPosition(0, 1400)
  await getGoodsEvaluateList()
}
// 翻页功能结束

// 导出
defineExpose({total})
</script>
  
<style scoped lang="scss">
.goods-evaluate-wrap {
  margin-bottom: 20px;
  .head {
    display: flex;
    padding: 30px 0;
    .data {
      width: 340px;
      display: flex;
      padding: 20px;
      p {
        flex: 1;
        text-align: center;
        span {
          display: block;
          &:first-child {
            font-size: 32px;
            color: $price-color;
          }
          &:last-child {
            color: #999;
          }
        }
      }
    }
    .tags {
      flex: 1;
      display: flex;
      border-left: 1px solid #f5f5f5;
      .dt {
        font-weight: bold;
        width: 100px;
        text-align: right;
        line-height: 42px;
      }
      .dd {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        > a {
          width: 132px;
          height: 42px;
          margin-left: 20px;
          margin-bottom: 20px;
          border-radius: 4px;
          border: 1px solid #e4e4e4;
          background: #f5f5f5;
          color: #999;
          text-align: center;
          line-height: 40px;
          &:hover {
            border-color: $main-color;
            background: lighten($main-color,50%);
            color: $main-color;
          }
          &.active {
            border-color: $main-color;
            background: $main-color;
            color: #fff;
          }
        }
      }
    }
  }

  // 过滤区域
  .filter-wrap {
    display: flex;
    justify-content: space-between;

    height: 60px;
    line-height: 60px;
    border-top: 1px solid #f5f5f5;
    border-bottom: 1px solid #f5f5f5;
    margin: 0 20px;
    color: #666;
    .filter-item {
      .title {
        font-weight: bold;
      }
    }
  }

  // 综合筛选区域
  .composite-filter-wrap {
    border-top: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
    padding: 10px 0;
    .composite-filter-item {
      .title {
        font-size: 16px;
        font-weight: bold;
        text-align: center;
      }
      .content {
        display: flex;
        flex-wrap: wrap;

        margin: 10px 0 30px 0;
        .sku-item {
          width: 24%;
          border: 1px solid #ccc;
          margin: 5px;
          text-align: center;
          height: 30px;
          line-height: 30px;
          cursor: pointer;
        }
        .active {
          border: 1px solid $main-color;
          color: $main-color;
        }
      }
    }
  }

  .list-wrap {
    padding: 0 20px;
    .item-wrap {
      padding: 25px 10px;
      border-bottom: 1px solid #f5f5f5;
      .top-wrap {
        display: flex;
        justify-content: space-between;
        .user-wrap {
          display: flex;
          align-items: center;
          img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            overflow: hidden;
          }
          span {
            padding-left: 10px;
            color: #666;
          }
        }
        .score-wrap {
          line-height: 40px;
          .iconfont {
            color: #ff9240;
            padding-right: 3px;
          }
          .attr {
            padding-left: 10px;
            color: #666;
          }
        }
      }
      .goods-sku-wrap {
        padding: 10px 0;
        color: #ccc;
      }
      .content-wrap {
        .content {
          color: #666;
          line-height: 24px;
        }
        .time-wrap {
          color: #999;
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-top: 10px;

          .action-wrap {
            display: flex;
            align-items: center;

            // 点赞区域
            .like-wrap {
              position: relative;
              .iconfont {
                font-size: 24px;
                padding-right: 4px;
                color: #999;
                cursor: pointer;
              }
              .like-tip{
                position: absolute;
                top: -10px;
                left: 0;
                opacity: 0;
                transition: all 0.3s;
                color: $main-color;
                /* 动画时间 */
                animation-duration: 0.3s;
              }
              .active {
                animation-name: give-like;
              }
              /* 定义动画 */
              @keyframes give-like {
                  /* 第一帧 */
                  0% {}

                  50% {
                    top: -30px;
                    opacity: 1;
                  }
                  /* 最后一帧 */
                  99% {
                    top: -40px;
                    opacity: 0;
                  }
                  /* 最后一帧 */
                  100% {
                    top: 0;
                    opacity: 0;
                  }
              }
            }

            // 评论
            .item-wrap {
              cursor: pointer;
              .iconfont {
                padding-right: 4px;
                font-size: 18px;
              }
            }

            // 有用
            .useful-wrap {
              cursor: pointer;
              .iconfont {
                padding-right: 4px;
                font-size: 18px;
              }
            }
            .active {
              color: $main-color;
            }
          }
        }
      }
    }
  }
  .empty-wrap {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px 0;
    img {
      width: 200px;
    }
    .txt {
      margin-top: 14px;
      color: #e4e4e4;
    }
  }

  .page-wrap {
    padding: 10px 0;
    display: flex;
    justify-content: center;
  }
}
</style>